import { getNewsDetail, labelQueryList, parentCode, submit, update, deleteDetail, getEstateList, downLoadFile, getMember, getCouponsList, getGiftList, getHouseList, getPayCodeList, formTemplatesList } from './activityDetailServ'
// 弹出消息框
import { message } from 'antd'
import { parse } from 'qs'
import { download } from 'utils/util'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import { makeAddress } from "utils/util"

// 初始默认状态
const state = {
    estateList: [],
    templatesList: [],
    TypeModalFlag: false,
    choiceType: '',
    choiceTypeTitle: '',
    hashUrl: '',
    btnLoading: false,
    skipType: '',
    fengmianList: [],
    editValue: 1,
    showEditor: true,
    disabledLink: true,
    productId: '',
    activityDetail: [],
    detail: {
        shelfStatus: false,
        isSelfTemplate: false,
        isPublishHouse: true,
        bottomImg: 'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/activity_bg_01.png',
        bottomImg2: 'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/activity_bg_01.png',
        bottomImgId: 'active-0',
        bottomImgId2: 'active-0',
    },
    tagALL: [],
    reaList: [],
    areaList: [],
    showTime: true,
    visible: false,
    contentId: '',
    Enroll: {},
    listData: [],
    imgModal: {
        visible: false,
        srcs: [],
    },
    gif: [
        'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/activity_bg_01.png',
        'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/activity_bg_02.png',
        'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/activity_bg_03.png',
        'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/activity_bg_04.png',
        'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/activity_bg_05.png',
    ],
    isSubmit: true,

    selectItem: [],
    //全选按钮
    indeterminate: false,
    checkAll: false,
    projectData: {
        province: '', //省
        city: '', //市
        productIds: [], //楼盘id
    },
    activityApply: { //活动报名对象
        receiptFlag: 0, //是否需要付款1是0否
        enrollFee: "", //报名费
        merchantCode: "", //收款商户编号
        enrollFormKeys: [], //报名填写信息
        enrollLimit: "", //报名人数限制
        showEnrolled: 0, //是否显示已报名人数1是0否
        relatProductType: 0, //关联商品分类0不限制1优惠卷2活动
        relatCouponId: "", //关联优惠卷ID
        relatGiftId: "", //关联礼品ID
        usageScope: 1, //适用范围分类1项目2区域3集团
        latAndLon: [],
    },
    discountCouponList: [], //优惠券列表
    giftList: [], //礼品列表
    payCodeList: [], //商户支付号列表
    Mapmodel: false,
    contentId: '', //活动专区id
}

//获取ant Images
function getImagesUrl(ImageList) {
    // console.log(ImageList)
    //返回一个数组
    let arr = []
    ImageList && ImageList.map((item, idx) => {
        // console.log(item.response.data.url)
        arr.push(item.response.data.url)
    })
    return arr
}
//生成ant Images 格式
function setImagesUrl(url) {
    //返回一个数组
    let arr = []
    arr.push({
        uid: -1,
        name: 'xxx.png',
        status: 'done',
        url: url
    })
    return arr
}

const tmpModule = {
    // namespace: 'infoAddOrEditModel',
    state: cloneDeep(state),
    subscriptions: {
        setup({ dispatch, history }) {
            history.listen(({ pathname, query }) => {
                let { actionType, contentId } = query
                if ('' + tmpModule.pathname === '' + pathname) {
                    //每次进来页面更新数据 重置state

                    dispatch({ type: 'getFormTemplatesList', payload: {...query } })
                    dispatch({ type: 'updateStore', payload: cloneDeep(state) });
                    dispatch({ type: 'updateStore', payload: { hashUrl: pathname } });
                    dispatch({ type: 'updateStore', payload: { actionType, contentId, activityId: contentId } });
                    dispatch({ type: 'getLabelQueryList', payload: {} });
                    dispatch({ type: 'getAreaList', payload: {} });
                    dispatch({ type: 'getCouponsList', payload: {} });
                    dispatch({ type: 'getGiftList', payload: {} });
                    dispatch({ type: 'getPayCodeList', payload: {} });
                    if (actionType == 'edit') {
                        dispatch({ type: 'estateInfo', payload: { actionType, contentId } });
                    } else if (actionType == 'detail') {
                        dispatch({ type: 'estateInfo', payload: { actionType, contentId } });
                        dispatch({ type: 'getEnroll', payload: { activityId: contentId, pageNo: 1, pageSize: 10 } });
                    }
                }
            })
        },
    },
    effects: {
        // 查询记录
        * estateInfo({ payload }, { put, call, select }) {
            let { contentId } = payload
            try {
                const { data, resultCode, resultMsg } = yield call(getNewsDetail, { contentId })
                let enrollFormKeys = [];
                let productIds = [];
                if (data.enrollFormKeys && data.enrollFormKeys.length > 0) {
                    data.enrollFormKeys = JSON.parse(data.enrollFormKeys);
                }
                if (data.productIds && data.productIds.length > 0) {
                    productIds = JSON.parse(data.productIds);
                }
                data.latAndLon = []
                data.latAndLon[0] = data.longitude
                data.latAndLon[1] = data.latitude
                let projectData = {
                    province: '', //省
                    city: '', //市
                    productIds: productIds
                };
                yield put({ type: 'updateStore', payload: { activityApply: data, projectData: projectData } })
                yield put({ type: 'houseList', payload: { productIds: productIds } })
                if (data.tags) {
                    let tagsArr = data.tags.split(';')
                    data.tags = tagsArr
                }
                let showTime = true
                if (data.channel == 3) {
                    showTime = false
                }
                let editValue = 1,
                    showEditor = 'block',
                    disabledLink = true
                if (data.linkFlag) {
                    editValue = 2
                    showEditor = 'none'
                    disabledLink = false
                }
                yield put({ type: 'updateStore', payload: { choiceTypeTitle: data.formTitle, choiceType: data.questionFormId, detail: data, showTime: showTime, editValue, showEditor, disabledLink } })
            } catch (e) {

            }
        },
        * houseList({ payload }, { put, call, select }) {
            let { selectItem } = yield select(state => state[tmpModule.namespace])
            const { success, msg, rows } = yield call(getHouseList, { productIds: payload.productIds, pageNo: 1, pageSize: 10000 });
            if (success) {
                yield put({
                    type: 'updateStore',
                    payload: {
                        selectItem: rows
                    }
                });
            }
        },
        * getEnroll({ payload }, { put, call, select }) {
            payload.channel = 3
            try {
                const { data } = yield call(getMember, payload)
                let listData = data.rows
                yield put({ type: 'updateStore', payload: { Enroll: data, listData } })
            } catch (e) {}
        },
        * downLoad({ payload }, { put, call, select }) {
            try {
                const { data, success, msg } = yield call(downLoadFile, parse(payload))

                if (success) {
                    let url = data || ''
                    if (url) {
                        download(url)
                    }
                } else {
                    message.error(`${msg}`)
                }
            } catch (e) {
                console.error(e)
            }
        },

        //获取标签列表
        * getLabelQueryList({ payload }, { put, call, select }) {
            try {
                const { rows } = yield call(labelQueryList, { type: 3, pageNo: 1, pageSize: 1000 })
                yield put({ type: 'updateStore', payload: { tagALL: rows } });
            } catch (e) {

            }
        },
        * getFormTemplatesList({ payload }, { put, call, select }) {
            payload.businessType = 'ACTIVITY_ENROLL';
            payload.status = 2
            try {
                let { success, rows } = yield call(formTemplatesList, {...payload })
                    // debugger
                if (success) {
                    yield put({ type: 'updateStore', payload: { templatesList: rows } })
                }
            } catch (e) {
                console.log('')
            }
        },
        //获取优惠券列表
        * getCouponsList({ payload }, { put, call, select }) {
            try {
                //admin/coupons/config/list
                const { rows, success } = yield call(getCouponsList, { scene: 3, status: 2 });
                if (success) {
                    if (rows) {
                        yield put({ type: 'updateStore', payload: { discountCouponList: rows } });
                    }
                }
            } catch (e) {

            }
        },
        * getPayCodeList({ payload }, { put, call, select }) {
            try {
                const { rows, success } = yield call(getPayCodeList, {});
                console.log(rows);
                if (success) {
                    if (rows) {
                        yield put({ type: 'updateStore', payload: { payCodeList: rows } });
                    }
                }
            } catch (e) {

            }
        },
        //获取礼品列表
        * getGiftList({ payload }, { put, call, select }) {
            try {
                //admin/coupons/config/list
                const { rows, success } = yield call(getGiftList, {});
                if (success) {
                    if (rows) {
                        yield put({ type: 'updateStore', payload: { giftList: rows } });
                    }
                }
            } catch (e) {

            }
        },
        //获取级联列表
        * getAreaList({ payload }, { put, call, select }) {
            try {
                const { data, success } = yield call(parentCode);
                if (success) {
                    let areaList = []
                    let arr = [data[0]]
                    let attr = [data[data.length - 1]]
                    data[0] = {
                        label: "北京",
                        value: "110100",
                        children: arr
                    }
                    data[data.length - 1] = {
                            label: "澳门",
                            value: "820000",
                            children: attr
                        }
                        //去掉第三级，
                    areaList = makeAddress(data, 2)
                    yield put({ type: 'updateStore', payload: { areaList } });
                }
            } catch (e) {

            }
        },
        //获取项目列表
        * getBusinessList({ payload }, { put, call, select }) {
            let params = {
                pageNo: 1,
                pageSize: 1000,
                ...payload
            }
            const data = yield call(getEstateList, params)
            let estateList = []
            if (data.success) {
                estateList = data.rows
            }
            yield put({ type: 'updateStore', payload: { estateList } });

        },
        * deleteContent({ payload }, { put, call, select }) {
            try {
                let { contentId } = yield select(state => state[tmpModule.namespace])
                console.log(contentId)
                yield put({ type: 'updateStore', payload: { loading: true, btnLoading: true, } })
                const data = yield call(deleteDetail, { 'contentId': contentId })
                yield put({ type: 'updateStore', payload: { loading: false, btnLoading: false, } })
                if (data.success) {
                    message.success('删除成功').then(() => {
                        hashHistory.push({ pathname: MODULE_TO_ROUTES[tmpModule.namespace].urlArray[1] })
                    });
                }
            } catch (e) {

            }
        },
        // 提交
        * submit({ payload }, { put, call, select }) {
            // type:
            // 保存 save
            // 发布 publish
            // 取消发布 unpublish
            try {
                let tmpState = yield select(state => state[tmpModule.namespace])
                let { detail, activityApply, projectData, choiceType, choiceTypeTitle } = tmpState;
                detail.channel = 3;
                //处理提交数据
                if (detail.tags && detail.tags.length != 0) {
                    let tagsStr = ''
                    let arr = detail.tags
                    arr.map((item, idx) => {
                        tagsStr = tagsStr + item + ';'
                    })
                    detail.tags = tagsStr.substr(0, tagsStr.length - 1)
                } else {
                    detail.tags = ''
                }

                if (detail.isSelfTemplate) {
                    delete detail.bottomImgId
                    delete detail.bottomImg2
                    delete detail.bottomImgId2
                    detail.selfTemplateImg && delete detail.selfTemplateImg
                }
                activityApply.longitude = activityApply.latAndLon && activityApply.latAndLon[0]
                activityApply.latitude = activityApply.latAndLon && activityApply.latAndLon[1]
                activityApply.enrollFormKeys = JSON.stringify(activityApply.enrollFormKeys);
                let params = {...detail, ...activityApply, ...projectData };

                if (!params.productIds || params.productIds == null || params.productIds.length == 0) {
                    message.error('请选择活动项目')
                    return false;
                }

                yield put({ type: 'updateStore', payload: { activityApply: activityApply } });
                //编辑或新增
                yield put({ type: 'updateStore', payload: { loading: true, btnLoading: true, } })

                if (!params.endDate) {
                    message.error('请选择结束时间')
                } else if (!params.titleImgUrl || typeof(params.titleImgUrl) == "undefined") {
                    message.error('请选择图片')
                } else {
                    params.questionFormId = choiceType
                    params.formTitle = choiceTypeTitle

                    //发布逻辑处理
                    // published type=='save'不处理
                    //取消发布 不保存修改数据
                    console.log('activityApply', activityApply)
                    if (payload.type == 'unpublish') {
                        params = { contentId: activityApply.contentId, published: 0 }
                    }
                    if (payload.type == 'publish') {
                        params.published = 1
                    }

                    // params.isSign = 0
                    if (payload.type == 'saveAndPublish') {
                        const { success, data } = yield call(submit, params)
                        if (success) {
                            params.contentId = data
                            params.published = 1
                            const rel = yield call(update, params)
                            if (rel.success) {
                                hashHistory.push({ pathname: MODULE_TO_ROUTES[tmpModule.namespace].urlArray[1] })
                                yield put({ type: 'estateInfo', payload: { contentId: params.contentId } });
                            }
                        }
                    } else {
                        let server = tmpState.actionType == 'add' ? submit : update

                        const data = yield call(server, params)
                        activityApply.enrollFormKeys = JSON.parse(activityApply.enrollFormKeys);
                        yield put({ type: 'updateStore', payload: { activityApply: activityApply } });
                        if (data.success) {
                            message.success('操作成功')
                                // yield put({ type: 'updateStore', payload: { estateList: [] } });
                            if (payload.type == 'save') {
                                hashHistory.push({ pathname: MODULE_TO_ROUTES[tmpModule.namespace].urlArray[1] })
                            } else {
                                yield put({ type: 'estateInfo', payload: { contentId: activityApply.contentId } });
                            }
                        } else {
                            message.error(data.resultMsg);
                        }
                    }

                }
                yield put({ type: 'updateStore', payload: { loading: false, btnLoading: false, } })

            } catch (e) {
                console.log(e)
            }
        },
        * updateModel({ payload }, { put, select }) {
            yield put({ type: 'updateStore', payload });
        },
        * dealEditor({ payload }, { put, select }) {
            let { detail, activityApply } = yield select(state => state[tmpModule.namespace])
            let newDetail = Object.assign({}, detail)
            newDetail.detail = payload.detail
            yield put({ type: 'updateStore', payload: { detail: newDetail, activityApply: newDetail } });
        },
    },

    // 存入状态机
    reducers: {
        updateStore(preState, action) {
            return {...preState, ...action.payload };
        }
    }
}

export default tmpModule